package com.bort.system.controller.admin;

import com.bort.system.model.User;
import com.bort.system.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@CrossOrigin
public class AdminAuthController {

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody Map<String, Object> user) {
        Result res = new Result();

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken((String) user.get("username"), (String) user.get("password"));
        Map<String, Object> data = new HashMap<>();

        if (!subject.isAuthenticated()) {
            try {
                subject.login(usernamePasswordToken);
                User currentUser = (User) subject.getPrincipal();
                data.put("userinfo", currentUser);
            } catch (LockedAccountException e) {
                res.setCode(0);
                res.setMsg("账号被禁用");
            } catch (IncorrectCredentialsException e) {
                res.setCode(0);
                res.setMsg("密码错误");
            } catch (DisabledAccountException e) {
                res.setCode(0);
                res.setMsg("不是管理员");
            } catch (UnknownAccountException e) {
                res.setCode(0);
                res.setMsg("账号不存在");
            } catch (AuthenticationException e) {
                res.setCode(0);
                res.setMsg("登录失败");
            }
        } else {
            User currentUser = (User) subject.getPrincipal();
            data.put("userinfo", currentUser);
        }
        res.setData(data);
        return res;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Result login() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.success();
    }

}
